# encoding: utf-8
class Admin::GroupsController < ApplicationController
  def index
    @groups = Group.find(:all)
    @page_title = 'Listing groups'    
  end

  def new
    @page_title = 'Create new group'
    @group = Group.new   
  end

  def create
    #debugger
    group_hash = {
      "j1P" => "初一",
      "j2P" => "初二",
      "j3P" => "初三",
      "s1P" => "高一",
      "s2W" => "高二文科",
      "s2L" => "高二理科",
      "s3W" => "高三文科",
      "s3L" => "高三理科"      
      }
    sex_hash ={
      "male" => "1",
      "female" => "2"     
    }
    team_code_array = []
    team_name_array = []
    projects = Project.where(:enabled => 1)
    group_code_array = []
    group_name_array = []
    sex_code_array = []
    sex_name_array = []
    project_code_array = []
    project_name_array = []
    setting_id = params[:group][:setting_id]
    # Set project matrix
    projects.each do |row|
      project_code_array.push(row.code)
      project_name_array.push(row.name)
    end
    # Set group matrix
    group_hash.each_with_index do |(key, value), index|
      if params[key.to_sym] == '1'      
        group_code_array.push(key)
        group_name_array.push(value)
      end
    end
    # Set sex matrix
    sex_hash.each_with_index do |(key, value), index|
      if params[key.to_sym] == '1'      
        sex_code_array.push(value)
        if value == '1'        
          sex_name_array.push("男子")
        else
          sex_name_array.push("女子")
        end
      end
    end
    # Set tem code
    group_code_array.each do |group_code|
      sex_code_array.each do |sex_code|
        project_code_array.each do |project_code|
          team_code_array.push(group_code + sex_code + project_code)
        end
      end
    end
    # Set team name
    group_name_array.each do |group_name|
      sex_name_array.each do |sex_name|
        project_name_array.each do |project_name|
          team_name_array.push(group_name + sex_name + project_name)
        end
      end
    end
    # Insert data
    fields = [:name, :code, :setting_id, :enabled]
    data = []  
    for i in 0..team_code_array.length-1 do
      data.push([team_name_array[i], team_code_array[i] , setting_id, true] )
    end
    if Group.import fields, data
      flash[:notice] = "Groups were successfully created."
    redirect_to :action => 'index'
    else
      @page_title = 'Create new groups'
      render :action => 'new'
    end
  end

  def destroy
  end

  def edit
    @group = Group.find(params[:id])
    @page_title = 'Edit group'
  end

  def show
    @group = Group.find(params[:id])
    @page_title = @group.name
  end

  def update
    @group = Group.find(params[:id])
    if @group.update_attributes(params[:group])
      flash[:notice] = "group #{@group.name} was successfully updated."
    redirect_to :action => 'show', :id => @group.id
    else
      @page_title = 'Edit group'
      render :action => 'edit'
    end
  end

end
